package shujia;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.HFileOutputFormat2;
import org.apache.hadoop.hbase.mapreduce.KeyValueSortReducer;
import org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles;
import org.apache.hadoop.hbase.mapreduce.SimpleTotalOrderPartitioner;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class Demo8BulkLoad {
    public static class BulkLoadMapper extends Mapper<LongWritable, Text, ImmutableBytesWritable, KeyValue> {
        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, ImmutableBytesWritable, KeyValue>.Context context) throws IOException, InterruptedException {

            String line = value.toString();
            String[] splits = line.split(",");

            String mdn = splits[0];
            String start_time = splits[1];
            // 经度
            String longitude = splits[4];
            // 维度
            String latitude = splits[5];

            String rowkey = mdn + "_" + start_time;

            // KeyValue相当于一个Cell
            KeyValue lgKV = new KeyValue(rowkey.getBytes(), "info".getBytes(), "lg".getBytes(), longitude.getBytes());
            KeyValue latKV = new KeyValue(rowkey.getBytes(), "info".getBytes(), "lat".getBytes(), latitude.getBytes());


            context.write(new ImmutableBytesWritable(rowkey.getBytes()), lgKV);
            context.write(new ImmutableBytesWritable(rowkey.getBytes()), latKV);
        }
    }

    // 因为不需要计算 Reduce任务可以省略

    // Driver端
    public static void main(String[] args) throws Exception {

        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "master:2181,node1:2181,node2:2181");

        Job job = Job.getInstance(conf);
        job.setJobName("Demo8BulkLoad");
        job.setJarByClass(Demo8BulkLoad.class);

        // 该配置不会生效，Reduce的任务由region的数量决定
        job.setNumReduceTasks(4);

        // 配置Map
        job.setMapperClass(BulkLoadMapper.class);
        job.setMapOutputKeyClass(ImmutableBytesWritable.class);
        job.setOutputValueClass(KeyValue.class);

        // 保证每个Reduce之间处理的数据不会有重叠 并且是有序的
        job.setPartitionerClass(SimpleTotalOrderPartitioner.class);

        // 配置Reduce
        // 保证在Reduce内部是有序的
        job.setReducerClass(KeyValueSortReducer.class);

        // 配置输入输出路径
        FileInputFormat.addInputPath(job, new Path("/bulk_load/input"));

        Path outputPath = new Path("/bulk_load/output");
        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(outputPath)) {
            fs.delete(outputPath, true);
        }
        FileOutputFormat.setOutputPath(job, outputPath);

        Connection conn = ConnectionFactory.createConnection(conf);
        Admin admin = conn.getAdmin();
        Table dianxin_bulk = conn.getTable(TableName.valueOf("dianxin_bulk"));

        RegionLocator regionLocator = conn.getRegionLocator(TableName.valueOf("dianxin_bulk"));

        // 第一步 生成HFile
        // 使用HFileOutputFormat2将输出的数据按照HFile的形式格式化
        HFileOutputFormat2.configureIncrementalLoad(
                job,
                dianxin_bulk,
                regionLocator
        );

        boolean flag = job.waitForCompletion(true);

        if (flag) {
            // 第二步 加载HFile到HBase中
            LoadIncrementalHFiles load = new LoadIncrementalHFiles(conf);
            load.doBulkLoad(
                    outputPath,
                    admin,
                    dianxin_bulk,
                    regionLocator
            );
        } else {
            System.out.println("MR任务运行失败");
        }
    }
    /**
     *  create 'dianxin_bulk','info',{SPLITS=>['1|','3|','5|','7|','9|','B|','D|']}
     *  hadoop jar HBase-1.0-jar-with-dependencies.jar shujia.Demo8BulkLoad
     */
}
